from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
import json
from web.models import Activity, User, ParticipationRecord, Reward
from django.core.paginator import Paginator
from django.utils import timezone
from django.forms.models import model_to_dict
from django import forms

class ActivityForm(forms.ModelForm):
    class Meta:
        model = Activity
        fields = ['title', 'description','cover_image', 'user_id','status']

@csrf_exempt
@require_http_methods(["POST"])
def create_activity(request):
    """创建活动"""
    try:
        data = request.POST
        user_id = data.get('user_id')
        
        try:
            user = User.objects.filter(user_id=user_id).first()
            if not user:
                return JsonResponse({'code': 401, 'message': '用户不存在'})
        except User.DoesNotExist:
            return JsonResponse({'code': 401, 'message': '用户不存在'})
            
        activity_form = ActivityForm(data=data, files=request.FILES)
        if activity_form.is_valid():
            # 批量创建1万条数据
            # for i in range(1000):
            #     activity = Activity.objects.create(
            #         title=f"活动{i}",
            #         description=f"活动{i}描述",
            #         cover_image="activities/bizhihui_com_20231111174608169969596899083.jpg",
            #         user_id=user,
            #         status="published"
            #     )
            #     # 奖励
            #     reward = Reward.objects.create(
            #         activity_id=activity.id,
            #         reward_name=f"奖励{i}",
            #         reward_type="points",
            #         quantity=1,
            #         remaining=1,
            #         image="rewards/bizhihui_com_20231111174608169969596899083.jpg",
            #     )
            #     print(f"创建第{i}条数据")

            activity = activity_form.save()
            # 返回创建数据
            activity_dict = model_to_dict(activity)
            activity_dict["created_at"] = activity.created_at.strftime("%Y-%m-%d %H:%M:%S")
            activity_dict["updated_at"] = activity.updated_at.strftime("%Y-%m-%d %H:%M:%S")
            activity_dict["cover_image"] = activity.cover_image.url if activity.cover_image else None
            return JsonResponse({'code': 200, 'message': '活动创建成功', 'data': activity_dict})
        else:
            print(activity_form.errors)
            return JsonResponse({'code': 400, 'message': '活动创建失败'})
        
     
    except Exception as e:
        return JsonResponse({'code': 500, 'message': str(e)})

@require_http_methods(["GET"])
def activity_list(request):
    """获取活动列表"""
    try:
        page = int(request.GET.get('page', 1))
        page_size = int(request.GET.get('page_size', 10))
        status = request.GET.get('status')
        
        activities = Activity.objects.all().order_by('-status')
        
        if status:
            activities = activities.filter(status=status)
            
        paginator = Paginator(activities, page_size)
        current_page = paginator.page(page)
        
        activity_list = [{
            'id': activity.id,
            'title': activity.title,
            'description': activity.description,
            'status': activity.status,
            'cover_image': activity.cover_image.url if activity.cover_image else None
        } for activity in current_page.object_list]
        
        return JsonResponse({
            'code': 200,
            'message': '获取成功',
            'data': {
                'total': paginator.count,
                'page': page,
                'page_size': page_size,
                'list': activity_list
            }
        })
    except Exception as e:
        return JsonResponse({'code': 500, 'message': str(e)}) 

@require_http_methods(["GET"])
def activity_detail(request):
    """获取活动详情"""
    try:
        activity_id = request.GET.get('activity_id')
        activity = Activity.objects.filter(id=activity_id).first()
        if not activity:
            return JsonResponse({'code': 404, 'message': '活动不存在'})
        
        activity_dict = model_to_dict(activity)
        activity_dict["created_at"] = activity.created_at.strftime("%Y-%m-%d %H:%M:%S")
        activity_dict["updated_at"] = activity.updated_at.strftime("%Y-%m-%d %H:%M:%S")
        activity_dict["cover_image"] = activity.cover_image.url if activity.cover_image else None
        return JsonResponse({'code': 200, 'message': '获取成功', 'data': activity_dict})
    except Exception as e:
        return JsonResponse({'code': 500, 'message': str(e)})
    

# 判断用户是否参与活动
@require_http_methods(["GET"])
def is_participated(request):
    """判断用户是否参与活动"""
    try:
        user_id = request.GET.get('user_id')
        activity_id = request.GET.get('activity_id')
        participation = ParticipationRecord.objects.filter(user_id=user_id, activity_id=activity_id).first()
        if participation:
            return JsonResponse({'code': 200, 'message': '获取成功', 'data': True})
        else:
            return JsonResponse({'code': 200, 'message': '获取成功', 'data': False})
    except Exception as e:
        return JsonResponse({'code': 500, 'message': str(e)})



# 搜索活动
@require_http_methods(["GET"])
def search_activity(request):
    """搜索活动"""
    try:
        keyword = request.GET.get('keyword')
        status = request.GET.get('status')
        page = int(request.GET.get('page', 1))
        page_size = int(request.GET.get('page_size', 10))
        
        # 构建查询
        activities = Activity.objects.all()
        
        # 关键词搜索
        if keyword:
            activities = activities.filter(title__icontains=keyword)
            
        # 状态筛选
        if status:
            activities = activities.filter(status=status)
            
        # 排序
        activities = activities.order_by('-created_at')
        
        # 分页
        paginator = Paginator(activities, page_size)
        current_page = paginator.page(page)
        
        activity_list = [{
            'id': activity.id,
            'title': activity.title,
            'description': activity.description,
            'status': activity.status,
            'cover_image': activity.cover_image.url if activity.cover_image else None,
            'created_at': activity.created_at.strftime("%Y-%m-%d %H:%M:%S")
        } for activity in current_page.object_list]
        
        return JsonResponse({
            'code': 200,
            'message': '获取成功',
            'data': {
                'total': paginator.count,
                'page': page,
                'page_size': page_size,
                'list': activity_list
            }
        })
    except Exception as e:
        return JsonResponse({'code': 500, 'message': str(e)})


# 编辑活动
@csrf_exempt
@require_http_methods(["POST"])
def edit_activity(request):
    """编辑活动"""
    try:
        data = request.POST
        activity_id = data.get('activity_id')
        activity = Activity.objects.filter(id=activity_id).first()
        if not activity:
            return JsonResponse({'code': 404, 'message': '活动不存在'})
        
        activity_form = ActivityForm(data=data, files=request.FILES, instance=activity)
        if activity_form.is_valid():
            activity_form.save()
            activity_dict = model_to_dict(activity)
            activity_dict["created_at"] = activity.created_at.strftime("%Y-%m-%d %H:%M:%S")
            activity_dict["updated_at"] = activity.updated_at.strftime("%Y-%m-%d %H:%M:%S")
            activity_dict["cover_image"] = activity.cover_image.url if activity.cover_image else None
            return JsonResponse({'code': 200, 'message': '活动编辑成功', 'data': activity_dict})
        else:
            print(activity_form.errors)
            return JsonResponse({'code': 400, 'message': '活动编辑失败'})
    except Exception as e:
        print(e)
        return JsonResponse({'code': 500, 'message': str(e)})
    

#